import { WechatService } from '@/services/wechat';
import { NextResponse } from 'next/server';
import { writeFile } from 'fs/promises';
import path from 'path';
import { mkdir } from 'fs/promises';

// 确保二维码存储目录存在
const QR_CODE_DIR = path.join(process.cwd(), 'public', 'qrcodes');

export async function POST(request: Request) {
  try {
    const { path: pagePath, env, type } = await request.json();
    console.log('Generating QR code with params:', { pagePath, env, type });

    // 创建存储目录（如果不存在）
    await mkdir(QR_CODE_DIR, { recursive: true });

    // 生成唯一的文件名
    const fileName = `car-mid-mp-${env}-${type}.png`;
    const filePath = path.join(QR_CODE_DIR, fileName);
    const publicPath = `/qrcodes/${fileName}`;

    const wechatService = WechatService.getInstance();
    const qrcodeBuffer = await wechatService.generateWXACode(pagePath, env, type);
    console.log('QR code buffer size:', qrcodeBuffer.length);

    // 保存二维码图片到文件系统
    await writeFile(filePath, qrcodeBuffer);
    console.log('QR code saved to:', filePath);

    // 返回图片的公共URL
    return NextResponse.json({
      url: publicPath,
      env,
      type,
    });
  } catch (error) {
    console.error('Error generating QR code:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to generate QR code' },
      { status: 500 }
    );
  }
}
